var hackathon = {

	init : function () {
		return new map();	
	}

};

var detail = (function(){

	var detailModel = new (Backbone.Model.extend({
		url : "http://119.147.8.121:8081/get_msg?",
		getDetail : function (opts) {
			this.fetch({
				jsonp:"jsonp",
				jsonpCallback:"json_get_msg",
				url:this.url+"tree_id="+opts.id,
				success : function(model,data){
					model.trigger("showDetail",data)
					//model.reset(data)
				}
			}) 
		}
	}));

	var detailView = Backbone.View.extend({
		initialize : function(){
			this.model.getDetail({id:this.id});
			this.model.bind("showDetail",this.render,this);
		},

		el : $("#details_page"),

		render : function (data) {
			$("#d_img").attr("src",data.img);
			$("#d_avatar").attr("src",data.avatar);
			$("#d_user").html(data.user);
			$("#d_article").html(data.article);
			$('#d_userimg').attr("src","images/1.png");
			$("#d_title").html(data.title);
			$("#d_tree").attr("src",'images/tree/tree_'+(parseInt(10/3*Math.random())*data.pri+1)+".png");
			var inner =[];
			var tmp = function(con){
				return [
					'<li>',
		              '<img class="commenter_avatar" src="'+con.avatar+'"></img>',
		              '<p><span class="commenter_name">'+con.user+'：</span><span class="comment_content">'+con.msg+'</span></p>',
		              '<p class="datetime">'+con.timestamp+'</p>',
		            '</li>',
				].join("");
			}
			for(var j=0;j<data.msg_list.length;j++){
				inner.push(tmp(data.msg_list[j]))
			}
			$('#comm').html(inner);
			$('#details_page').show(function(){$(this).addClass('details_page_show')})
				
			var model = new (Backbone.Model.extend({
				url:'http://119.147.8.121:8081/send_msg?user='+user+'&tree_id='+data.id,
				postData : function () {
					this.save(null,{
						url : encodeURI(this.url+'&msg='+document.getElementById('d_data').value),
						jsonpCallback:'json_send_msg',
						success : function () {
							var cache = $('#comm').html() || "";
							cache += tmp({
								avatar : 'images/1.png',
								user : user,
								msg : document.getElementById('d_data').value,
								timestamp : (new Date().toString()).slice(8,24)
							})
							$('#comm').html(cache);
							document.getElementById('d_data').value = "";
						}
					})
				}
			}));
			document.getElementById("d_finish").onclick=function(){
				
				model.postData();

			}
			document.getElementById("d_delete").onclick=function(){
				document.getElementById('d_data').value = "";
			}
			//this.$el.addClass('details_page_show')
			// this.$el
			// 	.html(this.template({
			// 		img : data.img,
			// 		article : data.article,
			// 		user : data.user,
			// 		avatar : data.avatar

			// 	}))
			// 	.addClass("details_page_show")
			// 	.bind("webkitTransitionEnd",function(){
			// 	    //$(this).removeClass("details_page_show");
			// 	})
		}
	});

	return (function(id){new detailView({id:id,model:detailModel})});

})();


var map = (function(){
	var models = new (Backbone.Model.extend({}));
		mapModel = new (Backbone.Collection.extend({
			url : "http://119.147.8.121:8081/query?",
			getMarker : function (opts) {
				this.fetch({
					jsonp:"jsonp",
					jsonpCallback:"json_query",
					url: this.url+"pos_x="+opts.pos_x+"&pos_y="+opts.pos_y+"&zoom="+opts.zoom,
					success : function(model,data){
						model.reset(data.data)
					}
				}) 
			},
			addMarker : function (opts) {
				var url = (function(opts){
					var _str = "http://119.147.8.121:8081/create?type=0&"+"pos_x="+opts.pos_x+"&pos_y="+opts.pos_y+"&title="+opts.title+"&user="+opts.user;

						return encodeURI(_str);
				})(opts);
				
				var that = this;
				models.save(null,{
					url:encodeURI(url),
					jsonp:"jsonp",
					jsonpCallback:"json_create",
					success : function (model,data) {
						models.trigger("newMarker",{},data.id);
					}
				})
			}
		})),

		moreData = new (Backbone.Model.extend({
			url:"http://119.147.8.121:8081/notify?",
			getNewData : function (userName) {
				this.fetch({
					jsonp:"json_notify",
					jsonpCallback:"json_notify",
					url:this.url+"user="+userName||"whoami",
					success : function(model,data){
						// for(var i = 0 , len = data.length; i < len ; i++) {
						// 	setTimeout((function(i){return function(){model.trigger("newMarker",data[i])}})(i),300);
						// }
						if(data.length > 0)
							moreData.trigger("newMarker",data[0])
					}
				}) 
			}
		})),

		mapView = Backbone.View.extend({
				user : (function(){
					var get = function(name) {
					      var r = new RegExp("(?:^|;+|\\s+)" + name + "=([^;]*)"), m = document.cookie.match(r);
					      return (!m ? "" : m[1]);
					    },
					    set = function(name, value, domain, path, hour) {
					      if (hour) {
					        var expire = new Date();
					        expire.setTime(expire.getTime() + 3600000 * hour);
					      }
					      document.cookie = name + "=" + value + "; " + (hour ? ("expires=" + expire.toGMTString() + "; ") : "") + (path ? ("path=" + path + "; ") : "path=/; ") + (domain ? ("domain=" + domain + ";") : ("domain=" + 'http://119.147.8.121:8081' + ";"));
					      return true;
					    },
					    _cacheUser;

					    if(_cacheUser = get("t_username")){
					    	return _cacheUser;
					    }    	
					    else {
					    	var newName = new Date().valueOf();
					    	 set("t_username",newName.toString()); 
					    	 return newName;
					    }
					
				})(),
				config : null,
				map : null,
				center : null,
				markerArr : [],
				initialize : function () {
					//get data about json [{title:""}] 
					var 
						that = this;
						window.user = this.user;
					//sent
					var cacheModel = new (Backbone.Model.extend({}));
					cacheModel.save(null,{
						url : 'http://119.147.8.121:8081/register?user='+this.user,
						jsonpCallback:"json_register",
						jsonp:"jsonp",
						success : function (model,data) {
						}
					});


					this.bindThis();
					this.infowindow = [];

					this.model.bind("reset",this.render,this);
					//this.model.bind("add",this.addMarker,this);
					models.bind("newMarker",this.newMarker,this);
					moreData.bind("newMarker",this.newMarker,this)
					this.getCurrentPos();
					
					document.getElementById('location').onclick = function () {
						that.setCenter();
					}
				},

				setCenter : function () {
					var pos = new google.maps.LatLng(this.center.latitude,this.center.longitude);
					this.map.setCenter(pos);
				},

				getCurrentPos :function () {
					var that = this;
					var x = document.body;
					function getLocation()
					  {
					  	
						  if (navigator.geolocation)
						    {
						    navigator.geolocation.getCurrentPosition(showPosition,showError);
						    }
						  else{x.innerHTML="Geolocation is not supported by this browser.";}
					  }
					function showPosition(position)
					  {
					  	var pos = {}

					  	pos.latitude = position.coords.latitude+Math.random()*Math.random()*0.09;
					  	pos.longitude = position.coords.longitude+Math.random()*Math.random()*0.08	;

					  	that.center = pos;
					 	that.model.getMarker({pos_x:pos.latitude,pos_y:pos.longitude,zoom:0});
					  }
					function showError(error)
					  {
					  	document.body.appendChild("<div style='height:200px;width:100px;position:absolute;left:10px;top:10px;'>error</div>");
					  switch(error.code) 
					    {
					    case error.PERMISSION_DENIED:
					      x.innerHTML="User denied the request for Geolocation."
					      break;
					    case error.POSITION_UNAVAILABLE:
					      x.innerHTML="Location information is unavailable."
					      break;
					    case error.TIMEOUT:
					      x.innerHTML="The request to get user location timed out."
					      break;
					    case error.UNKNOWN_ERROR:
					      x.innerHTML="An unknown error occurred."
					      break;
					    }
					  }
					  getLocation();
				},
				going:true,
				newMarker : function (opts,id) {
					var that = this;
						if(!that.going){
							return;
							setTimeout(function(){that.going = true;},15000)
						}
							this.setCenter();
							that.going = false;
							var 	
								that = this,
								opts = opts || {},
								_lat = opts.pos_x || that.center.latitude,
								_long = opts.pos_y ||that.center.longitude,
								_title = opts.title || "我的位置",
								_myLatlng = new google.maps.LatLng(_lat,_long),
								_cacheMarker = new google.maps.Marker({
								      position: _myLatlng,
								      map: that.map,
								      animation: google.maps.Animation.DROP,
								      title:_title,
								      zIndex : 1200
								  });

							_cacheMarker.id = opts.id || id;
							_cacheMarker.pri = opts.pri || 0;
							 _cacheMarker.img = opts.img || 'images/1.png';
							 _cacheMarker.title = _title;

							 var image = new google.maps.MarkerImage(opts.img || 'images/flag_00.png');
							 image.scaledSize = new google.maps.Size(40,50);
							 image.size = new google.maps.Size(40,50);
							 image.anchor = new google.maps.Point(20, 25);


							 _cacheMarker.setIcon(image);
							 _cacheMarker.setMap(that.map);
							 that.markerArr.push(_cacheMarker);

							that.setEvent(_cacheMarker,"click",function(event){that.showDetail(_cacheMarker)});
							that.setEvent(_cacheMarker,"touch",function(event){that.showDetail(_cacheMarker)});
				},
				render : function (model,data) {
					//make maps
					if(!this.center){
						alert("获取不到当前位置哦~~")
					}
					var that = this,map,
						myLatLng = new google.maps.LatLng(this.center.latitude, this.center.longitude),
					  
						  config = {
						    zoom: 14,
						    center: myLatLng,
						    mapTypeId: google.maps.MapTypeId.ROADMAP
						  };

						  map = this.map = new google.maps.Map(document.getElementById("map_canvas"),
						      config);
						 //this.setEvent(this.map,"click",this.postMarker);

						  setInterval(function(){
						  	moreData.getNewData(that.user);
						  },15000)

						  //set center
						  var that = this,
						  	addCenter = (function () {
						  	var 
								_lat = that.center.latitude,
								_long = that.center.longitude ,
								_title = "我的位置",
								_myLatlng = new google.maps.LatLng(_lat,_long),
								_cacheMarker = new google.maps.Marker({
								      position: _myLatlng,
								      map: that.map,
								      animation: google.maps.Animation.DROP,
								      title:_title,
								      zIndex : 105
								  });

							 var image = new google.maps.MarkerImage('images/position.png');
							 image.scaledSize = new google.maps.Size(40,50);
							 image.size = new google.maps.Size(40,50);
							 image.anchor = new google.maps.Point(20, 25);

							 _cacheMarker.setIcon(image);
							 _cacheMarker.setMap(that.map);
							
							
						  })()


						   google.maps.event.addListener(map, 'zoom_changed', function() {
							    var zoomLevel = map.getZoom();
							    if(zoomLevel < 13){
							    	clearOverlays(that.markerArr,that.infowindow);
							    	
							    } else {
							    	if(zoomLevel >= 14){
							    		that.showDetail(that.markerArr[i]);
							    	}
							    	showOverlays(that.markerArr,true);
							    	that.resetDetail();
							    }
						  });

						  for (var i =0; i < model.models.length; i++) {
						  	  	for(j in model.models[i].attributes){
						  	  		that.addMarker(model.models[i].attributes[j]);
						  	  	}
						      
						  }
						  function go() {
							  	
							  	for(var k = 0;k<9;k++ ){
							  		var i = Math.ceil(Math.random()*that.markerArr.length)-1;
						  				
						  			that.showDetail(that.markerArr[i]);
							  	}
							  //	setTimeout(go,15000);

						  }
						  setTimeout(go,200)		  		

						  // Removes the overlays from the map, but keeps them in the array
							function clearOverlays(markersArray,infowindow) {
							  if (markersArray) {
							    for (i in markersArray) {
							      if(markersArray[i].iw){
							      	markersArray[i].iw.hide();
							      }
							      markersArray[i].setMap(null);
							    }
							    for(i in infowindow){
							    	infowindow[i].hide();
							    }
							  }
							  showOverlays(markersArray);
							}

							// Shows any overlays currently in the array
							function showOverlays(markersArray,all) {
							  if (markersArray) {
							    for (i in markersArray) {
							    	if( markersArray[i].pri > 2){
							    		
							    		markersArray[i].setMap(map);
							    	}
							      
							    }
							  }
							  if(all) {
							  	for (i in markersArray) {
							    		markersArray[i].setMap(map);
							    		if(markersArray[i].iw){
									      	markersArray[i].iw.show();
									      }
							    	}
							  }
							}
				},

				custom : function (marker,image,map) {
					var pos = marker.getPosition();
					var swBound = new google.maps.LatLng(pos.Ya, pos.Za);
					  var neBound = new google.maps.LatLng(pos.Ya + 0.01, pos.Za + 0.005);
					  var bounds = new google.maps.LatLngBounds(swBound, neBound);

					function USGSOverlay(bounds, image, map) {

					  // Now initialize all properties.
					  this.bounds_ = bounds;
					  this.image_ = image;
					  this.map_ = map;

					  // We define a property to hold the image's
					  // div. We'll actually create this div
					  // upon receipt of the add() method so we'll
					  // leave it null for now.
					  this.div_ = null;

					  // Explicitly call setMap() on this overlay
					  this.setMap(map);
					}

					USGSOverlay.prototype = new google.maps.OverlayView();

					USGSOverlay.prototype.onAdd = function() {

					  // Note: an overlay's receipt of onAdd() indicates that
					  // the map's panes are now available for attaching
					  // the overlay to the map via the DOM.

					  // Create the DIV and set some basic attributes.
					  var div = document.createElement('div');
					  div.style.border = "none";
					  div.style.borderWidth = "0px";
					  div.style.position = "absolute";

					  var imgBg = document.createElement("img");
					  imgBg.src="images/tip_bg.png";
					  imgBg.setAttribute("style","width:250px;z-index:10;")
						div.appendChild(imgBg);

					  // Create an IMG element and attach it to the DIV.
					  var img = document.createElement("img");
					  img.src = this.image_;
					  img.style.width = "50px";
					  img.style.position = "absolute";
					  img.style.top = "20px";
					  img.style.left = "20px";
					  img.style.zIndex = "11";
					  
					  div.appendChild(img);

					  var p = document.createElement("p");
					  p.innerHTML = marker.title;
					  p.style.width = "150px";
					  p.style.position = "absolute";
					  p.style.left = "80px";
					  p.style.top = "20px";
					  div.appendChild(p);

					  div.onclick = function(){
					  	new detail(
					  		marker.id)
					  }
					  div.ontouch = function(){
					  	new detail(marker.id)
					  }
					 //  that.setEvent(infowindow,"click",function(event){});

						// that.setEvent(infowindow,"touch",function(event){new detail(infowindow.marker.id)});

					  // Set the overlay's div_ property to this DIV
					  this.div_ = div;

					  // We add an overlay to a map via one of the map's panes.
					  // We'll add this overlay to the overlayImage pane.
					  var panes = this.getPanes();
					  panes.overlayLayer.appendChild(div);
					}

					USGSOverlay.prototype.draw = function() {

					  // Size and position the overlay. We use a southwest and northeast
					  // position of the overlay to peg it to the correct position and size.
					  // We need to retrieve the projection from this overlay to do this.
					  var overlayProjection = this.getProjection();

					  // Retrieve the southwest and northeast coordinates of this overlay
					  // in latlngs and convert them to pixels coordinates.
					  // We'll use these coordinates to resize the DIV.
					  var sw = overlayProjection.fromLatLngToDivPixel(pos);

					  // Resize the image's DIV to fit the indicated dimensions.
					  var div = this.div_;
					  div.style.left = (sw.x- 10)+ 'px';
					  div.style.top = (sw.y - 110)- (marker.pri * 5) + 'px';
					  div.style.width = '250px';
					  div.style.height = '95px';
					 // div.style.height = (sw.y - ne.y - 100) + 'px';
					  div.style.zIndex = "105";
					  div.className +=" pop_tip";
					  div.parentNode.style.zIndex="110";
					  
					}

					USGSOverlay.prototype.onRemove = function() {
					  this.div_.parentNode.removeChild(this.div_);
					  this.div_ = null;
					}

					// Note that the visibility property must be a string enclosed in quotes
					USGSOverlay.prototype.hide = function() {
					  if (this.div_) {
					    this.div_.style.visibility = "hidden";
					  }
					}

					USGSOverlay.prototype.show = function() {
					  if (this.div_) {
					    this.div_.style.visibility = "visible";
					  }
					}

					USGSOverlay.prototype.toggle = function() {
					  if (this.div_) {
					    if (this.div_.style.visibility == "hidden") {
					      this.show();
					    } else {
					      this.hide();
					    }
					  }
					}

					USGSOverlay.prototype.toggleDOM = function() {
					  if (this.getMap()) {
					    this.setMap(null);
					  } else {
					    this.setMap(this.map_);
					  }
					}


					return (new USGSOverlay(bounds,image,map));
				},

				resetDetail : function () {

					for(var i in this.infowindow){
						if(!this.infowindow[i] && this.infowindow[i].marker){
							this.showDetail(this.infowindow[i].marker);
						}
					}
				},

				bindThis : function () {
					var that = this;
					this.showDetail = function (marker) {
						var opts = {};
						if(marker.showing){
							if(!marker.iw){
								return;
							}
							marker.showing = false;
							marker.iw.hide();
							marker.iw = null;
							var index = that.infowindow.indexOf(marker.iw);
							that.infowindow.splice(index,1);
							return;
						}
							
						opts.maxWidth = 50;

						var random;
						//show infowindow
						if(that.infowindow.length >=9) {
							that.infowindow.length = 9;
							random = Math.ceil(Math.random()*9)-1;
							if(that.infowindow[random]){
								that.infowindow[random].hide();
								that.infowindow[random].marker.iw = null;
								that.infowindow[random] = null;
							}	
							
						}


					    marker.showing = true;	
						var infowindow = that.infowindow[random||that.infowindow.length] = this.custom(marker,marker.img,that.map);
						infowindow.marker = marker;
						marker.iw = infowindow;
						
						
					},

					this.postMarker = function (topic) {

						var 
							opts = {
								pos_x : that.center.latitude,
								pos_y : that.center.longitude,
								title : "topic",
								type : 0,
								user : "tyson"
							};
						that.model.addMarker(opts);

					}

				},	
				
				addMarker : function (marker,newMarker) {

					var that = this,
						newMarker =(function (marker,that) {
							if(!that.map){
								return false;
							}
							var 
								_lat = marker.pos_x,
								_long = marker.pos_y ,
								_title = marker.title ,
								_id = marker.id,
								_pri = marker.pri,
								_img = marker.avatar || "images/1.png",
								_title = marker.title,
								_myLatlng = new google.maps.LatLng(_lat,_long),
								_cacheMarker = new google.maps.Marker({
								      position: _myLatlng,
								      map: that.map,
								      title:_title,
								      zIndex : 100
								  });

							 _cacheMarker.id = _id;
							 _cacheMarker.pri = _pri;
							 _cacheMarker.img = _img;
							 _cacheMarker.title = _title;

							 var image = new google.maps.MarkerImage('images/flag_'+_pri+'.png');
							 image.scaledSize = new google.maps.Size(40,50);
							 image.size = new google.maps.Size(40,50);
							 image.anchor = new google.maps.Point(20, 25);
							 var shadow = new google.maps.MarkerImage('http://upload.wikimedia.org/wikipedia/commons/3/3e/Tree-256x256.png',
							      new google.maps.Size(40, 50),
							      new google.maps.Point(_lat,_long),
							      new google.maps.Point(0, 32)
							  );


							 _cacheMarker.setIcon(image);
							// _cacheMarker.setShadow(shadow);
							that.markerArr.push(_cacheMarker);

							return _cacheMarker;
						})(marker,this);
					if(!newMarker){
						alert("地图loaded失败");
					}
					newMarker.setMap(this.map);
					this.setEvent(newMarker,"click",function(event){that.showDetail(newMarker)});
					this.setEvent(newMarker,"touch",function(event){that.showDetail(newMarker)});
					//后续注意多点触碰Warning
					
				},

				setEvent : function (marker,type,fun) {
					var addEvent = google.maps.event.addListener;

					addEvent(marker, type ,fun);
				},

				

				addInfoWindow : function () {
					var map;
					var infoWindow ;

					function initialize() {
					  var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
					  var mapOptions = {
					    zoom: 5,
					    center: myLatLng,
					    mapTypeId: google.maps.MapTypeId.TERRAIN
					  };

					  var bermudaTriangle;

					  map = new google.maps.Map(document.getElementById("map_canvas"),
					      mapOptions);

					  var triangleCoords = [
					    new google.maps.LatLng(25.774252, -80.190262),
					    new google.maps.LatLng(18.466465, -66.118292),
					    new google.maps.LatLng(32.321384, -64.75737)
					  ];

					  bermudaTriangle = new google.maps.Polygon({
					    paths: triangleCoords,
					    strokeColor: "#FF0000",
					    strokeOpacity: 0.8,
					    strokeWeight: 3,
					    fillColor: "#FF0000",
					    fillOpacity: 0.35
					  });

					  bermudaTriangle.setMap(map);

					  // Add a listener for the click event
					  google.maps.event.addListener(bermudaTriangle, 'click', showArrays);

					  infowindow = new google.maps.InfoWindow();
					}

					function showArrays(event) {

					  // Since this Polygon only has one path, we can call getPath()
					  // to return the MVCArray of LatLngs
					  var vertices = this.getPath();

					  var contentString = "<b>Bermuda Triangle Polygon</b><br />";
					  contentString += "Clicked Location: <br />" + event.latLng.lat() + "," + event.latLng.lng() + "<br />";

					  // Iterate over the vertices.
					  for (var i =0; i < vertices.length; i++) {
					    var xy = vertices.getAt(i);
					    contentString += "<br />" + "Coordinate: " + i + "<br />" + xy.lat() +"," + xy.lng();
					  }

					  // Replace our Info Window's content and position
					  infowindow.setContent(contentString);
					  infowindow.setPosition(event.latLng);

					  infowindow.open(map);
					}
				}

			});

	return (function(){
		return new mapView({model:mapModel});
	})
})();